import * as http from 'http'
import * as https from 'https'
import { logger } from './common'
import * as zlib from 'zlib'


export const Fetch = function <T = any>(url: string | URL, options: http.RequestOptions, body?: any) {
  return new Promise<T | undefined>((resolve) => {
      const client_req = (/^https:\/\//.test(url?.toString()) ? https : http).request(url, options, function (res) {
          if (res.statusCode != 200) {
              console.log('[Error]\t', url, res.statusMessage, options)
              res.resume()
              resolve(undefined)
          } else {
              let rawData: Buffer[] = []
              res.on('data', function (chunk) {
                  rawData.push(chunk)
              }).on('end', function () {
                  try {
                      let buffers = Buffer.concat(rawData)
                      if (res.headers['content-encoding'] === 'gzip') {
                        buffers = zlib.unzipSync(buffers)
                      }
                      const result = JSON.parse(buffers.toString('utf8'))
                      resolve(result)
                  } catch (e) {
                      logger.log('Error', url, e, rawData)
                      resolve(undefined)
                  }
              }).on('error', function (e) {
                  logger.log('Error', url, e)
                  resolve(undefined)
              })
          }
      }).on('timeout', function () {
          logger.log('Timeout', url)
          resolve(undefined)
      }).on('error', function (e) {
          logger.log('Error', url, e)
          resolve(undefined)
      })
      if (body) {
          client_req.write(body, function () {
              client_req.end()
          })
      } else {
          client_req.end()
      }
  })
}
